package puzzle.common.loader;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;

import puzzle.common.data.AbstractBoard;
import tomoto.io.StreamUtil;

public abstract class AbstractLoader<B extends AbstractBoard<B>> {
	private String m_separatorPattern;

	public AbstractLoader(String separatorPattern) {
		m_separatorPattern = separatorPattern;
	}

	public AbstractLoader() {
		this(null);
	}

	public B load(Reader r) throws IOException {
		String content = StreamUtil.readAll(r);

		Preprocessor pp;
		if (m_separatorPattern != null) {
			pp = new Preprocessor(m_separatorPattern);
		} else {
			pp = new Preprocessor();
		}

		if (content.contains("\n")) {
			pp.process(new StringReader(content));
		} else {
			// perhaps this is an nfp
			pp.process(new StringReader(NfpParser.extractData(content)));
		}

		return process(pp);
	}

	protected abstract B process(Preprocessor pp);

}
